import datetime
import os
import shutil
import time
import cv2.cv2
import VideoCase as vc
import builtins

# 手机录像目录
vfpath = "/sdcard/DCIM/Camera"
# 日期获取%Y-%m-%d-%H-%M-%S
date = time.strftime("%Y-%m-%d", time.localtime())
# 结果目录
resultpath = os.path.abspath(os.path.join(os.getcwd(), "..")) + "\Result" + "\\" + date


# 结果存放目录


# 导出文件
def pullfile(name):
    # 强制删除该文件夹
    print(str(datetime.datetime.now()) + " : " + "[" + vc.devicesid + "] " + "强制删除该文件夹" + resultpath + "\\" + name)
    shutil.rmtree(resultpath + "\\" + name, ignore_errors=True)
    # 导出录制视频
    time.sleep(3)
    print(str(datetime.datetime.now()) + " : " + "[" + vc.devicesid + "] " + "导出录制视频" + resultpath + "\\" + name)
    vc.adbpull(resultpath + "\\" + name)


# 1.30s模块  timel为时间
# 还原默认设置
# print(str(datetime.datetime.now()) + " : " + "[" + devicesid + "] " + "<--录制视频(完成)" + desc + ",时长为：" + timel)
def run30mod(timel, name, num):
    print(str(datetime.datetime.now()) + " : " + "[" + vc.devicesid + "] " + "视频模块开始: " + str(vc.timelformat(timel)))
    vc.openscreen_on()
    vc.device.shell(" rm -rf /sdcard/DCIM/Camera")
    vc.device.shell(" am force-stop com.android.camera")
    vc.device.app_start(vc.appname)
    time.sleep(1)
    vc.redefualtCamera()
    time.sleep(2)
    vc.video(timel, num, "off")
    vc.videoEis()
    vc.video(timel, num, "off")
    vc.device.shell(" am force-stop com.android.camera")
    # 慢动作
    vc.slowmotion(timel, num)
    print(str(datetime.datetime.now()) + " : " + "[" + vc.devicesid + "] " + "视频模块结束: " + str(vc.timelformat(timel)))
    pullfile(name)


# 2.full模块
def runfullmod(timel, name, num):
    print(str(datetime.datetime.now()) + " : " + "[" + vc.devicesid + "] " + "full视频模块开始：" + str(vc.timelformat(timel)))
    vc.openscreen_on()
    vc.device.shell(" rm -rf /sdcard/DCIM/Camera")
    vc.device.shell(" am force-stop com.android.camera")
    vc.device.app_start(vc.appname)
    time.sleep(1)
    vc.redefualtCamera()
    time.sleep(2)
    vc.video(timel, num, "off")
    vc.videoEis()
    vc.video(timel, num, "off")
    vc.device.shell(" am force-stop com.android.camera")
    # 慢动作
    vc.slowmotion(timel, num)
    # 画幅
    vc.device.shell(" am force-stop com.android.camera")
    vc.device.app_start(vc.appname)
    time.sleep(1)
    vc.videoEis()
    vc.video(timel, num, "on")
    vc.videoEis()
    vc.video(timel, num, "on")
    print(
        str(datetime.datetime.now()) + " : " + "[" + vc.devicesid + "] " + "full视频模块结束: " + str(vc.timelformat(timel)))
    pullfile(name)


# 3.5min模块
def run5minmod():
    run30mod(timel=300, name="5", num=1)


# 4.前置视频模式
def runfrontmod():
    vc.description("高清 720p, 30fps", timel=2, num=1, fullstatus="off", switch="front", beauty="on")
    print("front video")


# 5.专业视频模式
def professmod(timel, name, num):
    print("professional model strat")
    print(str(datetime.datetime.now()) + " : " + "[" + vc.devicesid + "] " + "专业视频模块开始: " + str(vc.timelformat(timel)))
    vc.openscreen_on()
    vc.device.shell(" rm -rf /sdcard/DCIM/Camera")
    vc.device.shell(" am force-stop com.android.camera")
    vc.device.app_start(vc.appname)
    time.sleep(1)
    vc.redefualtCamera()
    # 开始录制
    time.sleep(2)
    vc.perfess_switch("WIDE", mod="录像")
    vc.description("高清 720p, 30fps", timel, num)
    vc.description("全高清 1080p, 30fps", timel, num)
    vc.description("全高清 1080p, 60fps", timel, num)
    vc.description("超高清 4K, 30fps", timel, num)
    time.sleep(2)
    vc.perfess_switch("UW")
    vc.description("高清 720p, 30fps", timel, num)
    vc.description("全高清 1080p, 30fps", timel, num)
    time.sleep(2)
    vc.perfess_switch("MACRO")
    vc.description("高清 720p, 30fps", timel, num)
    # 结束录制
    print(str(datetime.datetime.now()) + " : " + "[" + vc.devicesid + "] " + "专业视频模块结束: " + str(vc.timelformat(timel)))
    pullfile(name)


# 6.短视频模式
def shortvideo(timel, name, num):
    print("short video strat")
    print(str(datetime.datetime.now()) + " : " + "[" + vc.devicesid + "] " + "short video strat: " + str(
        vc.timelformat(timel)))
    vc.openscreen_on()
    vc.device.shell(" rm -rf /sdcard/DCIM/Camera")
    vc.device.shell(" am force-stop com.android.camera")
    vc.device.app_start(vc.appname)
    time.sleep(1)
    vc.redefualtCamera()
    time.sleep(1)
    # 开始录制
    vc.switchmodel("短视频")
    vc.description("高清 720p, 30fps", timel, num, modelname="短视频")
    vc.description("全高清 1080p, 30fps", timel, num, modelname="短视频")
    vc.description("高清 720p, 30fps", timel, num, modelname="短视频", switch="front")
    vc.description("全高清 1080p, 30fps", timel, num, modelname="短视频")
    vc.description("高清 720p, 30fps", timel, num, modelname="短视频", switch="front", zoom=0.6)
    vc.description("全高清 1080p, 30fps", timel, num, modelname="短视频")
    # 结束录制
    print(str(datetime.datetime.now()) + " : " + "[" + vc.devicesid + "] " + "short video end: " + str(
        vc.timelformat(timel)))
    front_rearvideo(timel, name, num)
    # pullfile(name)


# 7.延时摄影模式
def timelapse(timel, name, num):
    print("timelapse video strat")
    print(str(datetime.datetime.now()) + " : " + "[" + vc.devicesid + "] " + "timelapse video strat: " + str(
        vc.timelformat(timel)))
    vc.openscreen_on()
    vc.device.shell(" rm -rf /sdcard/DCIM/Camera")
    vc.device.shell(" am force-stop com.android.camera")
    vc.device.app_start(vc.appname)
    time.sleep(1)
    vc.redefualtCamera()
    time.sleep(1)
    # 开始录制
    vc.switchmodel("延时摄影")
    vc.description("高清 720p, 30fps", timel, num, modelname="延时摄影", zoom=0.6)
    vc.description("全高清 1080p, 30fps", timel, num, modelname="延时摄影", zoom=0.6)
    vc.description("高清 720p, 30fps", timel, num, modelname="延时摄影", zoom=1.0)
    vc.description("全高清 1080p, 30fps", timel, num, modelname="延时摄影", zoom=1.0)
    vc.description("超高清 4K, 30fps", timel, num, modelname="延时摄影", zoom=1.0)
    time.sleep(1)
    vc.description("高清 720p, 30fps", timel, num, modelname="延时摄影", switch="front")
    vc.description("全高清 1080p, 30fps", timel, num, modelname="延时摄影")
    # 结束录制
    print(str(datetime.datetime.now()) + " : " + "[" + vc.devicesid + "] " + "timelapse video end: " + str(
        vc.timelformat(timel)))
    pullfile(name)


# 8.前后双景
def front_rearvideo(timel, name, num):
    print("fornt rear start")
    print(str(datetime.datetime.now()) + " : " + "[" + vc.devicesid + "] " + "fornt rear start: " + str(
        vc.timelformat(timel)))
    vc.openscreen_on()
    # vc.device.shell(" rm -rf /sdcard/DCIM/Camera")
    vc.device.shell(" am force-stop com.android.camera")
    vc.device.app_start(vc.appname)
    time.sleep(1)
    vc.redefualtCamera()
    time.sleep(1)
    # 开始录制
    vc.switchmodel("前后双景")
    vc.device.click(0.068, 0.549)
    vc.numcase(timel, num)
    vc.device.click(0.058, 0.144)
    time.sleep(2)
    vc.device.click(0.037, 0.138)
    vc.numcase(timel, num)
    # 结束录制
    print(str(datetime.datetime.now()) + " : " + "[" + vc.devicesid + "] " + "fornt rear end: " + str(
        vc.timelformat(timel)))
    pullfile(name)


# 9.萌拍模式
def faceumod(timel, name, num):
    print("faceu video start ")
    print(str(datetime.datetime.now()) + " : " + "[" + vc.devicesid + "] " + "faceu video start: " + str(
        vc.timelformat(timel)))
    vc.openscreen_on()
    vc.device.shell(" rm -rf /sdcard/DCIM/Camera")
    vc.device.shell(" am force-stop com.android.camera")
    vc.device.app_start(vc.appname)
    time.sleep(1)
    vc.redefualtCamera()
    time.sleep(1)
    # 开始录制
    vc.description(" ", timel, num, modelname="萌拍", shrotvideo="on", switch="rear")
    vc.description(" ", timel, num, modelname="萌拍", shrotvideo="on", switch="front")
    # 结束录制
    print(str(datetime.datetime.now()) + " : " + "[" + vc.devicesid + "] " + "faceu video end: " + str(
        vc.timelformat(timel)))
    pullfile(name)


# 10.超级防抖
def superEis2(timel, name, num):
    vc.description("全高清 1080p, 30fps", timel, num, modelname="录像", desc_shake="超级防抖，关闭状态")


def moremod(timel, name, num, supereis="off", faceu="off", fullstatus="off"):
    print(str(datetime.datetime.now()) + " : " + "[" + vc.devicesid + "] " + "视频模块开始: " + str(vc.timelformat(timel)))
    vc.openscreen_on()
    vc.device.shell(" rm -rf /sdcard/DCIM/Camera")
    vc.device.shell(" am force-stop com.android.camera")
    vc.device.app_start(vc.appname)
    time.sleep(1)
    vc.redefualtCamera()
    time.sleep(2)
    vc.video(timel, num, "off")
    if supereis == "on":
        vc.description("全高清 1080p, 30fps", timel, num, modelname="录像", desc_shake="超级防抖，关闭状态")
    if faceu == "on":
        vc.description(" ", timel, num, modelname="萌拍", shrotvideo="on", switch="rear")
    vc.videoEis()
    vc.video(timel, num, "off")
    if supereis == "on":
        vc.description("全高清 1080p, 30fps", timel, num, modelname="录像", desc_shake="超级防抖，关闭状态")
    if faceu == "on":
        vc.description(" ", timel, num, modelname="萌拍", shrotvideo="on", switch="rear")
    vc.device.shell(" am force-stop com.android.camera")
    # 慢动作
    vc.slowmotion(timel, num)
    # 是否开启画幅拍摄
    if fullstatus == "on":
        vc.redefualtCamera()
        vc.video(timel, num, fullstatus=fullstatus)
        vc.videoEis()
        vc.video(timel, num, fullstatus=fullstatus)
    print(str(datetime.datetime.now()) + " : " + "[" + vc.devicesid + "] " + "视频模块结束: " + str(vc.timelformat(timel)))
    pullfile(name)


# run test ------------------------------------------------------------------------------------------------
def runtest():
    # run30mod(timel=30, name="2", num=1)
    # run5minmod()
    runfullmod(timel=30, name="3", num=1)


def test():
    professmod(5, "8", 1)


def listdir(path):  # 传入存储的list
    datanames = os.listdir(path)
    file_list = []
    for dataname in datanames:
        if os.path.splitext(dataname)[-1] == '.mp4' or os.path.splitext(dataname)[-1] == '.avi':  # 目录下包含.json的文件
            file_list.append(dataname)
    return file_list


def anaylsis_one(filepath):
    woo = 0
    videoframes, lostframes = [], []
    for i in sortdir(filepath):
        print(filepath + "\\" + str(i))
        vCapture = cv2.VideoCapture(filepath + "\\" + str(i))
        status = True
        # 获取视频帧数
        frame_rate = round(vCapture.get(5), 3)
        # 每帧获取时间间隔列表
        interval = []
        # 获取上一帧时间戳,初始帧数时间戳为0
        pre = 0
        frame_count = 0
        timelist = []
        print("----------waiting to analysis-----------")
        while (status):
            time_start = time.time()
            # 获取视频帧
            # status, frame = vCapture.read()
            status = vCapture.grab()
            time_end = time.time()
            # 获取每帧时间戳
            cur = vCapture.get(cv2.CAP_PROP_POS_MSEC)
            # 计算每帧
            interval.append(float((cur - pre) / 1000))
            pre = cur
            timenum2 = time_end - time_start
            woo = float(woo + timenum2)
        print('Analyzing ' + str(vCapture.get(cv2.CAP_PROP_FRAME_COUNT)) + ' Frame.')
        # 总帧数
        frame_count = vCapture.get(cv2.CAP_PROP_FRAME_COUNT)
        # 获取最大丢帧时间戳间隔
        peak_value = round(max(interval), 5)
        # 计算最大丢帧数=(最大丢帧时间戳间隔/单位帧时间戳间隔)-1
        # print(str(peak_value) + "   " + str(frame_rate))
        if frame_rate != 30:
            lost_frame = (float(peak_value) / (float((1 / frame_rate)))) - 1
        elif frame_rate == 30:
            lost_frame = 0
        # print("max_lost_frame: " + str(lost_frame))
        videoframes.append(str(frame_rate))
        lostframes.append(str(lost_frame))
    # print("总时间:" + str(round(woo, 5)))
    return videoframes, lostframes


def one_viedoframe():
    print("\n开始执行Camera测试")
    filepath = r"D:\PyCharmProject\pythonDemo2\Result\2021-11-05\6\Camera"
    cv2.VideoCapture(filepath)
    for i in listdir(filepath):
        print(cv2.VideoCapture(filepath + "\\" + str(i)).get(5))
        print(str(cv2.VideoCapture(filepath + "\\" + str(i)).get(cv2.CAP_PROP_FRAME_COUNT)))


# time sort file
def sortdir(filepath):
    reio = os.popen(r"dir /A-D /OD  /B " + filepath).read()
    reio = str(reio).split('\n')
    del (reio[-1])
    return reio


def runCase():
    run30mod(30, "4", 1)
    moremod(30, "1", 1, supereis="on", faceu="off", fullstatus="off")
    moremod(30, "2", 1, supereis="on", faceu="on", fullstatus="on")
    moremod(30, "3", 1, supereis="off", faceu="on", fullstatus="on")
    professmod(2, "8", 1)
    shortvideo(2, "9", 1)
    timelapse(2, "10", 1)
    faceumod(2,"11",1)

if __name__ == '__main__':
    print("----------------------------------------------------------")
    # print(sortdir(r"W:\Python\10-31\pythonDemo2\Result\2021-11-10\2"))
    # print(get_file_list(r"D:\PyCharmProject\pythonDemo2\Result\2021-11-05\6\Camera"))
    # print(listdir(r"D:\PyCharmProject\pythonDemo2\Result\2021-11-05\6\Camera"))
    # shortvideo(0,"1",1)
    # timelapse(2,"6",1)
    # faceumod(15, "3", 1)
    # superEis2(2, "4", 1)
    # vc.description("全高清 1080p, 30fps", 2, 1, modelname="录像", desc_shake="超级防抖，关闭状态")
    # moremod(2,"6",1,supereis="on",faceu="on",fullstatus="off")
